package com.qiaofei.controller.api;

import com.qiaofei.pojo.OldHouse;
import com.qiaofei.pojo.PageBean;
import com.qiaofei.pojo.Result;
import com.qiaofei.service.impl.OldHouseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 出售管理Controller
 */
@Slf4j
@RestController
@RequestMapping("/api/oldhouses")
public class OldHouseController extends BaseController{

    @Autowired
    private OldHouseServiceImpl oldHouseService;

    @GetMapping
    public Result page(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer pageSize,
                       String title, Short estateId,
                       @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
                       @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end){
        log.info("分页查询, 参数: {},{},{},{},{},{}",page,pageSize,title,estateId,begin,end);
        //调用service分页查询
        Map<String, Object> params = new HashMap<>();
        params.put("title", title);
        params.put("estate", estateId);

        PageBean pageBean = oldHouseService.page(page,pageSize,params,begin,end);
        return Result.success(pageBean);
    }

    /**
     * 新增
     * @return
     */
    @PostMapping
    public Result add(@RequestBody OldHouse oldHouse){
        log.info("新增: {}" , oldHouse);
        //调用service新增
        int result = oldHouseService.add(oldHouse);
        return Result.success(result);
    }

    /**
     * 编辑
     * @param oldHouse
     * @return
     */
    @PutMapping
    public Result update(@RequestBody OldHouse oldHouse){
        log.info("编辑出租信息: {}" , oldHouse);
        //调用service
        oldHouseService.update(oldHouse);
        return Result.success();
    }

    /**
     * id查询
     * @param ids
     * @return
     */
    @GetMapping("/{ids}")
    public Result getByIds(@PathVariable List<Integer> ids){
        log.info("id查询, id:{}",ids);
        List<OldHouse> oldHouseList = oldHouseService.getByIds(ids);
        return Result.success(oldHouseList);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids){
        log.info("批量删除操作, ids:{}",ids);
        int result = oldHouseService.delete(ids);
        if(result > 0) {
            return Result.success();
        }else{
            return Result.error("删除失败");
        }
    }
}
